package com.nx.service.impl;

import com.mongodb.client.result.UpdateResult;
import com.nx.entity.User;
import com.nx.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class UserService implements IUserService {

	@Autowired
    private MongoOperations mongoOperations;
	
	/*@Autowired
    private MongoTemplate mongoTemplate;*/
	
	//save存在则更新，不存在则插入
	public void save(User user){
		mongoOperations.save(user);
	}

	//insert存在则不做处理，不存在则插入
	public void insert(User user){
	    mongoOperations.insert(user);
	}

	//根据userid删除文档
	public void remove(String uid){
	    Query query = new Query();
	    query.addCriteria(Criteria.where("userid").is(uid));
	    mongoOperations.remove(query,User.class); 
	}

	//根据id更新文档
	public UpdateResult update(User user){
	    Query query = new Query();
	    query.addCriteria(Criteria.where("userid").is(user.getUserid()));
	    Update update = new Update();
	    update.set("name",user.getName());
	    update.set("age",user.getAge());
	    return  mongoOperations.updateFirst(query, update,User.class); //只修改第一个数据
	    //return mongoOperations.updateMulti(query,update,User.class).getN();   //修改所有符合数据
		 
	}

	//单条件查询，find查询所有
	public List<User> findByUid(String uid){
	    Query query = new Query();
	    query.addCriteria(Criteria.where("userid").is(uid));
	    return mongoOperations.find(query,User.class);
	}

	//多条件查询，find查询所有
	public List<User> findByUidAndTimestamp(String uid,String name){
	    Query query = new Query();
	    query.addCriteria(Criteria.where("userid").is(uid).and("name").is(name));
	    return mongoOperations.find(query,User.class);
	}

	//根据uid分页查询
	public List<User> page(int page,String uid){
	    Query query = new Query();
	    query.addCriteria(Criteria.where("userid").is(uid));
	    query.with(new Sort(new Sort.Order(Sort.Direction.DESC,"age")));
	    query.limit(5);
	    query.skip((page-1)*2);
	    return mongoOperations.find(query,User.class);
	}


} 